import { fabric } from 'fabric';
import { EraserBrush } from './eraser';

// let canvas = null;
import pencil from '../../../assets/teaching/pencil.png';
import eraser from '../../../assets/eraser.svg';
import { getStorage } from '../../../utils/tools';

// let canvas = null;
let rect = {};
let mouseFrom = {};
let mouseTo = {};
let drawingObject = null;
let moveCount = 1; // 绘制移动计数器
let doDrawing = false; // 绘制状态
window.zoom = window.zoom ? window.zoom : 1;
let o = {};

// 坐标转换
function transformMouse(mouseX, mouseY) {
  return { x: mouseX / window.zoom, y: mouseY / window.zoom };
}
// 绘制箭头方法
function drawArrow(fromX, fromY, toX, toY, theta, headlen) {
  theta = typeof theta !== 'undefined' ? theta : 30;
  headlen = typeof theta !== 'undefined' ? headlen : 10;
  // 计算各角度和对应的P2,P3坐标
  const angle = (Math.atan2(fromY - toY, fromX - toX) * 180) / Math.PI;
  const angle1 = ((angle + theta) * Math.PI) / 180;
  const angle2 = ((angle - theta) * Math.PI) / 180;
  const topX = headlen * Math.cos(angle1);
  const topY = headlen * Math.sin(angle1);
  const botX = headlen * Math.cos(angle2);
  const botY = headlen * Math.sin(angle2);
  let arrowX = fromX - topX;
  let arrowY = fromY - topY;
  let path = ` M ${fromX} ${fromY}`;
  path += ` L ${toX} ${toY}`;
  arrowX = toX + topX;
  arrowY = toY + topY;
  path += ` M ${arrowX} ${arrowY}`;
  path += ` L ${toX} ${toY}`;
  arrowX = toX + botX;
  arrowY = toY + botY;
  path += ` L ${arrowX} ${arrowY}`;
  return path;
}
const newCanvas = (page) => {
  const c = new fabric.Canvas(`canvas${page}`);
  c.on('path:created', ({ path } = {}) => {
    if (path) {
      path.selectable = false;
    }
  });
  return c;
};

// const start = null;
// const down = false;
export default function xzCanvas(vm) {
  // const isone = true;
  const { page, iconDraw: icon, colorDraw, sizeDraw, clearDraw } = vm;
  if (icon === 'guanbi') {
    o = {};
    return;
  }
  // 有缓存读取缓存（*）
  o[`canvas${page}`] = o[`canvas${page}`] || newCanvas(page);
  const canvas = o[`canvas${page}`];
  canvas.defaultCursor = 'crosshair';
  // 在任何模式下都可以 清空画布
  if (clearDraw) {
    // console.log('清空画布');
    canvas.clear();
    vm.clearDraw = false;
    return;
  }
  if (icon === 'brush') {
    // console.log('画笔');
    canvas.isDrawingMode = true;
    canvas.freeDrawingBrush = new fabric.PencilBrush(canvas);
    canvas.freeDrawingBrush.color = colorDraw;
    canvas.freeDrawingBrush.width = sizeDraw;
    canvas.freeDrawingCursor = `url(${pencil}),auto`;
  } else if (icon === 'eraser') {
    // console.log('橡皮擦');
    // 任务栏高度
    const taskHeight = getStorage('taskHeight') || 0;
    // console.log('taskHeight =====> ', taskHeight);
    // 让箭头指向居中位置
    canvas.freeDrawingCursor = `url(${eraser}) ${taskHeight / 2} ${taskHeight / 2}, auto`;

    // canvas.freeDrawingCursor = `url(${eraser}),auto`;
    canvas.isDrawingMode = true;
    const eraserBrush = new EraserBrush(canvas);
    eraserBrush.width = 30;
    eraserBrush.color = 'rgba(225, 225, 225, 1)';
    canvas.freeDrawingBrush = eraserBrush;
  } else if (icon === 'toolCabinet') {
    // console.log('工具箱');
    canvas.isDrawingMode = false;
    canvas.freeDrawingCursor = '';
    mouseFrom = {};
    mouseTo = {};
  }

  // 画图
  function drawing(icon) {
    if (drawingObject) {
      canvas.remove(drawingObject);
    }
    rect = null;
    const numMaxX = Math.max(mouseFrom.x, mouseTo.x);
    const numMaxY = Math.max(mouseFrom.y, mouseTo.y);
    const numMinX = Math.min(mouseFrom.x, mouseTo.x);
    const numMinY = Math.min(mouseFrom.y, mouseTo.y);
    const minX = Math.min(numMaxY - numMinY, numMaxX - numMinX); // 宽高最小边距
    if (icon === 'iconxuxian') {
      canvas.isDrawingMode = false;
      canvas.freeDrawingCursor = 'crosshair';
      rect = new fabric.Line([mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y], {
        strokeWidth: sizeDraw,
        stroke: colorDraw,
        strokeDashArray: [5, 3],
      });
      // drawingObject = rect;
    } else if (icon === 'iconzhixian') {
      canvas.isDrawingMode = false;
      canvas.freeDrawingCursor = 'crosshair';
      rect = new fabric.Line([mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y], {
        strokeWidth: sizeDraw,
        stroke: colorDraw,
      });
    } else if (icon === 'iconyuan') {
      canvas.isDrawingMode = false;
      rect = new fabric.Circle({
        radius: minX / 2,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        left: numMinX,
        top: numMinY,
      });
    } else if (icon === 'icontuoyuan') {
      canvas.isDrawingMode = false;
      rect = new fabric.Ellipse({
        rx: (numMaxX - numMinX) / 2,
        ry: (numMaxY - numMinY) / 2,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        angle: 0,
        left: numMinX,
        top: numMinY,
      });
      // rect = new fabric.Circle({
      //   radius: minX / 1.2,
      //   stroke: colorDraw,
      //   fill: '',
      //   scaleY: 0.5,
      //   strokeWidth: 2,
      //   left: numMinX,
      //   top: numMinY,
      // });
    } else if (icon === 'iconzhengfangxing') {
      canvas.isDrawingMode = false;
      rect = new fabric.Rect({
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        width: minX,
        height: minX,
      });
    } else if (icon === 'iconyuanjiaojuxing') {
      canvas.isDrawingMode = false;
      rect = new fabric.Rect({
        left: numMinX,
        top: numMinY,
        fill: '',
        width: minX,
        height: minX,
        strokeWidth: sizeDraw,
        stroke: colorDraw,
        rx: 10,
        ry: 10,
      });
    } else if (icon === 'iconjuxing') {
      rect = new fabric.Rect({
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        width: numMaxX - numMinX,
        height: numMaxY - numMinY,
      });
    } else if (icon === 'iconlingxing') {
      canvas.isDrawingMode = false;
      rect = new fabric.Rect({
        left: numMinX + minX / 2,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        width: minX / 1.5,
        height: minX / 1.5,
        angle: 45,
      });
    } else if (icon === 'icondengbiansanjiaoxing') {
      canvas.isDrawingMode = false;
      const temp = minX / 2;
      const points = [
        {
          x: numMinX + minX / 2,
          y: numMinY - temp * 1.732,
        },
        {
          x: numMinX,
          y: numMinY,
        },
        {
          x: numMinX + minX,
          y: numMinY,
        },
      ];
      rect = new fabric.Polygon(points, {
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
      // rect = new fabric.Triangle({
      //   width: minX,
      //   height: minX / 2 * 1.732,
      //   fill: '',
      //   left: numMinX,
      //   top: numMinY,
      //   stroke: 'red',
      //   strokeWidth: 2,
      // });
    } else if (icon === 'icondengyaosanjiaoxing') {
      canvas.isDrawingMode = false;
      const points = [
        {
          x: numMinX,
          y: numMinY,
        },
        {
          x: numMinX,
          y: numMinY + minX,
        },
        {
          x: numMinX + minX,
          y: numMinY + minX,
        },
      ];
      rect = new fabric.Polygon(points, {
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
    } else if (icon === 'iconwubianxing') {
      canvas.isDrawingMode = false;
      const temp = minX / 2;
      const points = [
        {
          x: numMinX + minX / 2,
          y: numMinY,
        },
        {
          x: numMinX + minX,
          y: numMinY + temp * 0.75,
        },
        {
          x: numMinX + minX - temp * 0.37,
          y: numMinY + temp * 1.85,
        },
        {
          x: numMinX + temp * 0.37,
          y: numMinY + temp * 1.85,
        },
        {
          x: numMinX,
          y: numMinY + temp * 0.75,
        },
      ];
      rect = new fabric.Polygon(points, {
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
    } else if (icon === 'iconliubianxing') {
      canvas.isDrawingMode = false;
      const temp = minX / 2;
      const points = [
        {
          x: numMinX + minX / 2,
          y: numMinY,
        },
        {
          x: numMinX + minX,
          y: numMinY + temp * 0.57,
        },
        {
          x: numMinX + minX,
          y: numMinY + temp * 0.57 * 3,
        },
        {
          x: numMinX + minX / 2,
          y: numMinY + temp * 0.57 * 4,
        },
        {
          x: numMinX,
          y: numMinY + temp * 0.57 * 3,
        },
        {
          x: numMinX,
          y: numMinY + temp * 0.57,
        },
      ];
      rect = new fabric.Polygon(points, {
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
    } else if (icon === 'icontixing') {
      canvas.isDrawingMode = false;
      const points = [
        {
          x: numMinX + (numMaxX - numMinX) * 0.25,
          y: numMinY,
        },
        {
          x: numMinX,
          y: numMinY + minX,
        },
        {
          x: numMaxX,
          y: numMinY + minX,
        },
        {
          x: numMinX + (numMaxX - numMinX) * 0.75,
          y: numMinY,
        },
      ];
      rect = new fabric.Polygon(points, {
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
    } else if (icon === 'iconpinghangsibianxing') {
      canvas.isDrawingMode = false;
      const points = [
        {
          x: numMinX + minX * 0.35,
          y: numMinY,
        },
        {
          x: numMinX,
          y: numMaxY,
        },
        {
          x: numMaxX - minX * 0.35,
          y: numMaxY,
        },
        {
          x: numMaxX,
          y: numMinY,
        },
      ];
      rect = new fabric.Polygon(points, {
        left: numMinX,
        top: numMinY,
        fill: '',
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
    } else if (icon === 'iconxingxing') {
      canvas.isDrawingMode = false;
      rect = new fabric.Path(
        `M ${(170.0 * minX) / 150} ${(210.0 * minX) / 150}L ${(217.023 * minX) / 150} ${(234.721 * minX) / 150} L ${
          (208.042 * minX) / 150
        } ${(182.361 * minX) / 150} L ${(246.085 * minX) / 150} ${(145.279 * minX) / 150} L ${(193.511 * minX) / 150} ${
          (137.639 * minX) / 150
        } L ${(170.0 * minX) / 150} ${(90.0 * minX) / 150} L ${(146.489 * minX) / 150} ${(137.639 * minX) / 150} L ${
          (93.915 * minX) / 150
        } ${(145.279 * minX) / 150} L ${(131.958 * minX) / 150} ${(182.361 * minX) / 150} L ${(122.977 * minX) / 150} ${
          (234.721 * minX) / 150
        } L ${(170.0 * minX) / 150} ${(210.0 * minX) / 150}`,
        { left: numMinX, top: numMinY, stroke: colorDraw, strokeWidth: sizeDraw, fill: '' },
      );
    } else if (icon === 'iconjiantou') {
      canvas.isDrawingMode = false;
      rect = new fabric.Path(drawArrow(mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y, 30, 30), {
        stroke: colorDraw,
        fill: 'rgba(255,255,255,0)',
        strokeWidth: sizeDraw,
      });
    } else if (icon === 'iconhuxian') {
      canvas.isDrawingMode = false;
      rect = new fabric.Circle({
        radius: minX / 2,
        left: numMinX + minX,
        top: numMinY + minX,
        angle: 180,
        endAngle: Math.PI / 2,
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        fill: '',
      });
    } else if (icon === 'iconduihuakuang') {
      canvas.isDrawingMode = false;
      const tuoyuan = new fabric.Circle({
        radius: minX / 2,
        stroke: colorDraw,
        fill: '',
        scaleY: 0.5,
        strokeWidth: sizeDraw,
        left: numMinX,
        top: numMinY,
        angle: 180,
        startAngle: (-Math.PI * 4) / 8.5,
        endAngle: (Math.PI * 11) / 7.9,
      });
      // canvas.add(rect);
      const line1 = new fabric.Line(
        [
          numMinX - (minX * 27) / 50 - sizeDraw,
          numMinY - (minX * 1) / 128 - sizeDraw * 0.5,
          numMinX - minX * 0.7,
          numMinY + minX / 5,
        ],
        {
          stroke: colorDraw,
          strokeWidth: sizeDraw / 2,
        },
      );
      const line2 = new fabric.Line(
        [
          numMinX - (minX * 33) / 100 - sizeDraw / 2,
          numMinY - (minX * 5) / 200 - sizeDraw * 0.5,
          numMinX - minX * 0.7,
          numMinY + minX / 5,
        ],
        {
          stroke: colorDraw,
          strokeWidth: sizeDraw / 2,
        },
      );
      rect = new fabric.Group([tuoyuan, line1, line2], {
        left: numMinX,
        top: numMinY,
        angle: 0,
      });
    } else if (icon === 'iconbanyuan') {
      canvas.isDrawingMode = false;
      const circle = new fabric.Circle({
        radius: minX / 2,
        left: numMinX,
        top: numMinY,
        angle: 0,
        startAngle: Math.PI,
        endAngle: 0,
        stroke: colorDraw,
        strokeWidth: sizeDraw,
        fill: '',
        selectable: true,
      });
      let maxX = 0;
      if (sizeDraw === 4) {
        maxX = numMinX + minX + 4;
      } else if (sizeDraw === 8) {
        maxX = numMinX + minX + 8;
      } else if (sizeDraw === 12) {
        maxX = numMinX + minX + 12;
      }
      const line = new fabric.Line([numMinX, numMinY + minX / 2, maxX, numMinY + minX / 2], {
        stroke: colorDraw,
        strokeWidth: sizeDraw,
      });
      rect = new fabric.Group([circle, line], {
        left: numMinX,
        top: numMinY,
        angle: 0,
      });
    }
    if (rect) {
      // canvasObject.index = getCanvasObjectIndex();
      canvas.add(rect); // .setActiveObject(canvasObject)
      drawingObject = rect;
    }
  }

  const boxDiv = document.getElementById('shanchu');
  // 画笔，橡皮擦，工具箱
  if (icon !== 'brush' && icon !== 'eraser' && icon !== 'toolCabinet') {
    // console.log('执行这里');
    vm.mouseDown = (options) => {
      const offsetX = options.e.offsetX || options.e.targetTouches[0].pageX;
      const offsetY = options.e.offsetY || options.e.targetTouches[0].pageY;
      const xy = transformMouse(offsetX, offsetY);
      boxDiv.style.display = 'none';
      mouseFrom.x = xy.x;
      mouseFrom.y = xy.y;
      doDrawing = true;
    };
    vm.mouseUp = (options) => {
      const offsetX = options.e.offsetX || options.pointer.x;
      const offsetY = options.e.offsetY || options.pointer.y;
      canvas.defaultCursor = '';
      if (options.target) {
        const { target } = options;
        // if( target.get('type')==='path')
        if (!target.selectable) {
          const xy = transformMouse(offsetX, offsetY);
          mouseTo.x = xy.x;
          mouseTo.y = xy.y;
          drawingObject = null;
          moveCount = 1;
          doDrawing = false;
          vm.iconDraw = '';
          return;
        }
        vm.target = target;
        const { aCoords } = target;
        const numY = Math.max(aCoords.br.y, aCoords.bl.y, aCoords.tr.y, aCoords.tl.y);
        const numX = Math.max(aCoords.br.x, aCoords.bl.x, aCoords.tr.x, aCoords.tl.x);
        boxDiv.style.position = 'fixed';
        boxDiv.style.left = `${numX - 30}px`;
        boxDiv.style.top = `${numY + 10}px`;
        boxDiv.style.background = '#FC8B09';
        boxDiv.style.color = '#FFF';
        boxDiv.style.display = 'block';
        boxDiv.onclick = () => {
          canvas.remove(target);
          boxDiv.style.display = 'none';
        };
      }

      const xy = transformMouse(offsetX, offsetY);
      mouseTo.x = xy.x;
      mouseTo.y = xy.y;
      drawingObject = null;
      moveCount = 1;
      doDrawing = false;
      vm.iconDraw = '';
    };
    vm.mouseMove = (options) => {
      if (moveCount % 2 && !doDrawing) {
        // 减少绘制频率
        return;
      }
      moveCount++;
      const offsetX = options.e.offsetX || options.e.targetTouches[0].pageX;
      const offsetY = options.e.offsetY || options.e.targetTouches[0].pageY;
      const xy = transformMouse(offsetX, offsetY);
      mouseTo.x = xy.x;
      mouseTo.y = xy.y;
      drawing(vm.iconDraw);
      // vm.iconDraw = '';
    };
    vm.keyupDel = (e) => {
      // 此处填写你的业务逻辑即可
      if (e.keyCode === 8 || e.keyCode === 46) {
        canvas.remove(vm.target);
        boxDiv.style.display = 'none';
      }
    };

    // console.log(`canvas${page} ===============> `, document.getElementById(`canvas${page}`))
    // 执行此方法前，请确保已经获取到id canvasX
    canvas.off('mouse:down', vm.mouseDown);
    canvas.off('mouse:move', vm.mouseMove);
    canvas.off('mouse:up', vm.mouseUp);
    document.removeEventListener('keyup', vm.keyupDel);
    canvas.on('mouse:down', vm.mouseDown);
    canvas.on('mouse:move', vm.mouseMove);
    canvas.on('mouse:up', vm.mouseUp);
    document.addEventListener('keyup', vm.keyupDel);
  }
}
